// websocket.js
class UniWebSocket {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.messageHandlers = [];
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
  }

  connect() {
    return new Promise((resolve, reject) => {
      // 微信小程序环境
      if (uni.getSystemInfoSync().platform === 'mp-weixin') {
        this.socket = wx.connectSocket({
          url: this.url,
          success: () => {
            console.log('WebSocket 连接建立');
            this.setupEventListeners();
            resolve();
          },
          fail: (err) => {
            console.error('WebSocket 连接失败', err);
            reject(err);
          }
        });
      } 
      // H5或App环境
      else {
        this.socket = new WebSocket(this.url);
        this.socket.onopen = () => {
          console.log('WebSocket 连接建立');
          this.reconnectAttempts = 0;
          resolve();
        };
        this.socket.onerror = (error) => {
          console.error('WebSocket 错误', error);
          reject(error);
        };
        this.setupEventListeners();
      }
    });
  }

  setupEventListeners() {
    const socket = this.socket;
    
    // 统一消息事件
    const onMessage = (event) => {
      const message = event.data || event;
      console.log('收到消息:', message);
      this.messageHandlers.forEach(handler => handler(message));
    };

    // 微信小程序
    if (uni.getSystemInfoSync().platform === 'mp-weixin') {
      socket.onMessage(onMessage);
      socket.onClose(() => {
        console.log('WebSocket 连接关闭');
        this.handleReconnect();
      });
    } 
    // H5/App
    else {
      socket.onmessage = onMessage;
      socket.onclose = () => {
        console.log('WebSocket 连接关闭');
        this.handleReconnect();
      };
    }
  }

  send(message) {
    if (this.isConnected()) {
      if (uni.getSystemInfoSync().platform === 'mp-weixin') {
        wx.sendSocketMessage({
          data: typeof message === 'object' ? JSON.stringify(message) : message
        });
      } else {
        this.socket.send(typeof message === 'object' ? JSON.stringify(message) : message);
      }
    } else {
      console.warn('WebSocket 未连接');
    }
  }

  isConnected() {
    if (!this.socket) return false;
    if (uni.getSystemInfoSync().platform === 'mp-weixin') {
      return this.socket.readyState === wx.WebSocket.OPEN;
    }
    return this.socket.readyState === WebSocket.OPEN;
  }

  addMessageHandler(handler) {
    this.messageHandlers.push(handler);
  }

  removeMessageHandler(handler) {
    this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
  }

  close() {
    if (this.socket) {
      if (uni.getSystemInfoSync().platform === 'mp-weixin') {
        wx.closeSocket();
      } else {
        this.socket.close();
      }
    }
  }

  handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
      setTimeout(() => this.connect(), this.reconnectInterval);
    }
  }
}

export default UniWebSocket;